<template>
  <div class="container-fluid">
    <header/>
  </div>

  <div>
    <add-qrcode v-if="!activeQrcode" @createQrcode="createQrcodeHandle" @loadQrcodeList="loadQrcodeListHandle"/>
    <update-qrcode
        v-if="activeQrcode"
        @createQrcode="createQrcodeHandle"
        @updateQrcode="updateQrcodeHandle"
        @cancel="cancelUpdateQrcodeHandle"
        :activeQrcode="activeQrcode"
        :isUpdate="update"/>

    <draggable v-model="qrcodeList" class="el-row" item-key="timestamp">
      <template #item="{ element }">
        <div class="card-box el-col-xl-4">
          <qrcode-item :qrcode="element" @editItem="editItemHandle" @deleteItem="deleteItemHandle"/>
        </div>
      </template>
    </draggable>
  </div>

</template>

<script>
import Header from '@/components/Header'
import AddQrcode from '@/components/AddQrcode'
import UpdateQrcode from '@/components/UpdateQrcode'
import QrcodeList from "@/components/QrcodeList";
import QrcodeItem from "@/components/QrcodeItem";
import Store from 'store2'
import draggable from 'vuedraggable'

import {QRCODE_STORE_PRE_KEY} from '@/config/constant'

export default {
  name: 'App',
  data() {
    return {
      activeQrcode: null,
      qrcodeList: [],
    }
  },
  components: {
    UpdateQrcode,
    AddQrcode,
    Header,
    QrcodeList,
    draggable,
    QrcodeItem
  },
  created() {
  },
  computed: {
    update() {
      return !!this.activeQrcode
    },
  },
  methods: {
    // click Create Btn handle
    createQrcodeHandle(param) {
      if (!param || !param.title || !param.contents) {

        this.$toast({
          message: 'Fail：Empty title or empty content',
        })

      }
      const filterTime = this.filterQrcodeList(param)
      if (filterTime) {

        this.$toast({
          message: `Fail: Existed! Create Time: ${this.getDateTimeFromTimestamp(filterTime)} `,
        })

      }
      // reset
      this.activeQrcode = null
      this.qrcodeList = [param].concat(this.qrcodeList)
      this.saveToStorage()
    },
    // check isExisted
    filterQrcodeList(param) {
      const len = this.qrcodeList.length
      for (let i = 0; i < len; i++) {
        const item = this.qrcodeList[i]
        if (item.title === param.title && item.link === param.link) {
          return item.timestamp
        }
      }
      return false
    },
    // format timestamp
    getDateTimeFromTimestamp(timestamp) {
      if (!timestamp) return ''
      const d = new Date(timestamp)
      return `${d.toLocaleString()}`
    },
    // Edit icon click handle
    editItemHandle(param) {
      debugger
      const len = this.qrcodeList.length
      for (let i = 0; i < len; i++) {
        const item = this.qrcodeList[i]
        if (item.timestamp === param.timestamp) {
          this.activeQrcode = item
        }
      }
    },
    // Cancel Update click handle
    cancelUpdateQrcodeHandle() {
      this.activeQrcode = null
    },
    // Update click Handle
    updateQrcodeHandle(param) {
      const tmpList = this.qrcodeList
      const len = tmpList.length
      for (let i = 0; i < len; i++) {
        const item = tmpList[i]
        if (item.title === param.title && item.link === param.link) {

          this.$toast({
            message: 'Fail: Existed',
          })

          return
        }
        if (item.timestamp === param.timestamp) {
          tmpList[i].title = param.title
          tmpList[i].link = param.link
        }
      }
      // update data
      this.qrcodeList = tmpList
      this.saveToStorage()
      // reset
      this.activeQrcode = null
    },
    // delete Item handle
    deleteItemHandle(param) {
      const tmpList = this.qrcodeList
      const newList = []
      const len = tmpList.length
      for (let i = 0; i < len; i++) {
        const item = tmpList[i]
        if (item.title === param.title && item.link === param.link && item.timestamp === param.timestamp) {
          continue
        } else {
          newList.push(item)
        }
      }
      // update data
      this.qrcodeList = newList
      this.saveToStorage()
      // reset
      this.activeQrcode = null
    },
    // store list to Storage
    saveToStorage() {
      this.$nextTick(() => {
        // get Date to as key
        const date = new Date()
        const key = QRCODE_STORE_PRE_KEY + date.toLocaleDateString()
        Store.set(key, this.qrcodeList)
      })
    },
    // load list from storage
    loadQrcodeListHandle(datePram) {
      // ElMessageBox.confirm('The operation will replace the current List!', 'Are you sure?', {
      //   confirmButtonText: 'Yes,Load',
      //   cancelButtonText: 'Cancel',
      //   type: 'info',
      // }).then(() => {
      //   console.log(datePram)
      //   let date = new Date()
      //   let keyDate = new Date(datePram).toLocaleDateString() || date.toLocaleDateString()
      //   const key = QRCODE_STORE_PRE_KEY + keyDate
      //   const list = Store.get(key)
      //   if (list) {
      //     this.qrcodeList = list
      //   } else {
      //     ElNotification({
      //       title: 'Error',
      //       message: 'List is Empty',
      //       type: 'error',
      //     })
      //   }
      // })
    },
    // dragend handle
    dragListEndHandle(list) {
      this.qrcodeList = list
      this.saveToStorage()
    },
  },
}
</script>

<style>
#app {
  font-family: 'Avenir', Helvetica, Arial, sans-serif;
  -webkit-font-smoothing: antialiased;
  -moz-osx-font-smoothing: grayscale;
  text-align: center;
  color: #2c3e50;
}

.card-box {
  padding: 5px;
}
</style>
